<!DOCTYPE html>
<html lang="zh-CN">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <link rel="stylesheet" href="../bootstrap.css">
</head>
<!-- 文件上传地址 http://www.liulongbin.top:3006/api/upload/avatar  -->

<body>
    <input type="file" id="filess">
    <button>上传</button><br>
    <img src="" alt="">
    <div class="progress" style="width:300px; margin: 15px;">
        <div class="progress-bar progress-bar-striped active" style="width: 0%;" id="prcent">
            0%
        </div>
    </div>
    <script src="../jquery copy.js"></script>
    <script>
        var res_url;
        $('button').on('click', function () {
            /* 获取上传文件列表 */
            var filess = $('#filess')[0].files
            console.log(filess);
            var data = new FormData()
            data.append('avatar', filess[0])
            /* 发送ajax前 当发送ajax时事件 */
            $(document).ajaxStart(function () {
                $('img').prop('src', '../loading.gif')
            })


            $.ajax({
                type: 'post',
                url: 'http://www.liulongbin.top:3006/api/upload/avatar',
                /* 取消默认这是请求头 */
                contentType: false,
                /* 提交时不会序列化data */
                processData: false,
                timeout: 8000,
                data: data,
                error(error) {
                    return alert('请求超时')
                },
                success(res) {
                    if (res.status !== 200) {
                        return alert('上传失败')
                    }
                    res_url = 'http://www.liulongbin.top:3006' + res.url
                },
                xhr() {
                    var xhr = new XMLHttpRequest
                    xhr.upload.addEventListener('progress', function (e) {
                        var procentComplete = Math.ceil((e.loaded / e.total) * 100) + '%'
                        console.log(procentComplete);
                        $('#prcent').css('width', procentComplete)
                        $('#prcent').html(procentComplete)

                    })
                    return xhr
                }
            })

            /* ajax发送完成之后 */
            $(document).ajaxStop(function () {
                if ($('img').prop('src', res_url)) {
                    $('#prcent').css('width', '0px')
                    $('#prcent').html('0%')
                }

            })

        })
    </script>

</body>

</html>